package com.xyy.saas.payment.callback.core.handler;

import com.alibaba.fastjson.JSONObject;
import com.jddglobal.open.client.DefaultSpiJddClient;
import com.xyy.saas.payment.adpater.jdCredit.req.JDNotifyReq;
import com.xyy.saas.payment.adpater.jdCredit.support.JdCreditClientFactory;
import com.xyy.saas.payment.cores.enums.ResultCodeEnum;
import com.xyy.saas.payment.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;

/**
 * @author liujf
 */
@Slf4j
public abstract class JDCallbackHandler<T extends JDNotifyReq> {
    @Autowired
    private RedisUtil redisUtil;

    public abstract String getMethod();

    public abstract JDNotifyReq parseRequest(String content);

    public abstract String createLockKey(String bizNo);

    public void trySetNx(String bizNo) {
        String key = createLockKey(bizNo);
        if (!redisUtil.setNx(key, "1", 10)) {
            throw new RuntimeException(ResultCodeEnum.PROFIT_SHARING_REPEAT_REQUEST.getMsg());
        }
    }

    public void callbackHandle(HttpServletRequest request) throws Exception {
        DefaultSpiJddClient defaultSpiJddClient = JdCreditClientFactory.getDefaultSpiJddClient();
        String bizContent = defaultSpiJddClient.receive(request);
        log.info("JDCallbackHandler.callbackHandle bizContent={}", bizContent);
        JDNotifyReq jdNotifyReq = parseRequest(bizContent);
        jdNotifyReq.checkParam();

        trySetNx(jdNotifyReq.getBizNo());
        doHandle((T) jdNotifyReq);
    }

    public abstract void doHandle(T t);

}
